#######################################################
# 因为pysnowball默认没有安装，所以要加载路径
import sys
import os

# 获取当前文件的绝对路径
current_file_path = os.path.abspath(__file__)
# 获取当前文件所在的目录
current_dir = os.path.dirname(current_file_path)
# 获取上一个目录
parent_dir = os.path.dirname(current_dir)

# 将上一个目录添加到 sys.path
sys.path.append(parent_dir)

########################################################

from pysnowball import utls, kline
from pysnowball.token import set_token
import time
import pandas as pd

from pymongo.errors import ConnectionFailure
from pymongo import MongoClient

# 股票代码信息
stock_code = "01610"
stock_type = "hk"


# MongoDB连接字符串
uri_standard = "mongodb://m001-student:m001-mongodb-basics@sandbox-shard-00-00.j7cll.mongodb.net:27017,sandbox-shard-00-01.j7cll.mongodb.net:27017,sandbox-shard-00-02.j7cll.mongodb.net:27017/myFirstDatabase?ssl=true&replicaSet=atlas-7b25e1-shard-0&authSource=admin"

timestamp = time.time()
time_str = time.strftime("%Y-%m-%d", time.gmtime(timestamp))


set_token(
    f"""Cookie: ssxmod_itna=7qRxRDBGqWwrG0D2iKD2Dy7DIrDwrxBP01DpOxQ5DODLxn+xGdDuiLK3hxiq9QFaN4bKeb5tQDBkImiDnqD8UDQeDv4gb54D0GwxqeeYlqEmOuntqvFqSitivFmliGeTOmK7GQUmcSskiYExiTiBxDoxGkDiHoD0FYYe4DxxDCaS7oDD4D5xDWDWPbF+gI3SrQh0KzK2a8bAnqSB0FzESk=QGe93htKWD4KApteGTYC2eTzzQuCEuiWzOI83PDXxika4i1=4GCD0+IvIfmUDkCAXHYQn5K8Ep1YseN/DnjuUz7XEhqQNGF4D; ssxmod_itna2=7qRxRDBGqWwrG0D2iKD2Dy7DIrDwrxBP01DpOxQ5DODLxn+xGdDuiLK3hxiq9QFaN4bKebHYDiP4DQhF9noTIb06LyXxM7AwxnU3PD; is_overseas=0; Hm_lpvt_1db88642e346389874251b5a1eded6e3={int(timestamp)}; Hm_lvt_1db88642e346389874251b5a1eded6e3=1746830075,1747013846,1747121836; u=1722485700; xq_a_token=c658a36d018fa1b72e8ab2966930c758ef61c92a; xq_id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOjE3MjI0ODU3MDAsImlzcyI6InVjIiwiZXhwIjoxNzQ5ODgyODU4LCJjdG0iOjE3NDcyOTA4NTgwMzcsImNpZCI6ImQ5ZDBuNEFadXAifQ.HkJrutlIuOJ-9WVJaRn-C7nFkGTdihQZkNX7D_9mHBila0SdhP_XogTPNBdcs-d5eDj5FfYGnQF9tvKkiIOpVgzUYduvVmCJ7Lyp2rCv9xUo1DEfjXEeme52nsq5cyBx27PvxTQnervvjfLJ6anVjT4NPlgiM-m2a9HZYKSR7TRr7Y6isZo88A0CzcfQmQz7P-sRKbK23GRbvegUdLiXrvULcF9FJcK-iU1TbpIVPExZfYtO9Y-yh5NzkMYS_3rRjpunsLvXv0CsYxNEEn4-yg4D2IIB-Nod1dmtcdCvVpXLc3-149z05C_dkotqezOl2orLIGbMiWlKYA2dS2onWg; xq_is_login=1; xq_r_token=ad0d376ac7a438436167b92898adfe17477e5180; xqat=c658a36d018fa1b72e8ab2966930c758ef61c92a; HMACCOUNT=0AB57BF4565EDB36; bid=caac5a2413778029e28cecde0bbeef0e_makin3vw; remember=1; s=bt14a6viaz; device_id=e4e07ac11188f65462d570317b1fb482; cookiesu=731746830073296"""
)

try:
    server_info = kline(stock_code, period="1m", count=360)

except Exception as e:
    print(f"Error fetching data: {e}")


pd_data = pd.DataFrame(
    server_info["data"]["item"], columns=server_info["data"]["column"]
)

pd_data_day = pd_data[pd_data["timestamp"] > utls.get_stamp_from_time(time_str)]

data_day_dict = pd_data_day.to_dict(orient="records")

day_data = {"datetime": time_str, "1m_data": data_day_dict}

try:
    client = MongoClient(uri_standard, connectTimeoutMS=5000)  # 设置5秒超时
    client.server_info()  # 触发连接测试

    print("连接成功！")
except ConnectionFailure as e:
    print(f"连接失败：{e}")

db = client["stocks"]
collection = db[stock_type + stock_code]
result = collection.insert_one(day_data)
print(f"Inserted document with id: {result.inserted_id}")
# 关闭MongoDB连接
client.close()
